package com.lms.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-16 10:16
 * @Description: 数据处理类
 */
public class  NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
    * @Author 李孟帅
    * @Description 读取数据，进行处理
    * @Date 2020/6/16 
    **/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("server ctx:"+ctx);
//        ByteBuf buf = (ByteBuf) msg;
//        System.out.println("客户端发送的消息是："+buf.toString(CharsetUtil.UTF_8));
//        System.out.println("客户端地址："+ctx.channel().remoteAddress());

//        异步处理  任务队列
//        Thread.sleep(5000);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,client",CharsetUtil.UTF_8));
//        System.out.println("go on ...");

        ctx.channel().eventLoop().execute(()->{
            try {
                System.out.println("Thread"+Thread.currentThread().getName());
                Thread.sleep(5000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,client",CharsetUtil.UTF_8));
                System.out.println("go on ...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        ctx.channel().eventLoop().schedule(()->{
            try {
                System.out.println("Thread"+Thread.currentThread().getName());
                Thread.sleep(5000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,client",CharsetUtil.UTF_8));
                System.out.println("go on ...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },5, TimeUnit.SECONDS);

    }

    /**
    * @Author 李孟帅
    * @Description 数据读取完毕
    * @Date 2020/6/16 
    **/
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //数据写入缓冲区并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello:客户端", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
